import { API_BASE_URL, handleApiResponse, type ApiResponse } from './config'
import md5 from 'md5'

// 登录请求参数
export interface LoginRequest {
  loginName: string | null
  loginPassword: string | null
}

// 登录响应数据
export interface LoginResponse {
  account: string
  token: string
}

// 登录接口
export const login = async (params: LoginRequest): Promise<LoginResponse> => {
  try {
    // 对密码进行MD5加密
    const encryptedParams = {
      loginName: params.loginName,
      loginPassword: params.loginPassword ? md5(params.loginPassword) : null
    }
    
    const response = await fetch(`${API_BASE_URL}/account/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(encryptedParams)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<LoginResponse>(response)
  } catch (error) {
    console.error('登录失败:', error)
    throw error
  }
}